using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using Microsoft.Feeds.Interop;

namespace FeedStore2OPML
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            

            OPML opml = CreateOpml();

            XmlSerializer serializer = new XmlSerializer(typeof(OPML));
            MemoryStream m = new MemoryStream();
            serializer.Serialize(m, opml);
            m.Seek(0, SeekOrigin.Begin);
            textBox1.Text = new StreamReader(m).ReadToEnd();
            m.Close();
        }

        private static OPML CreateOpml()
        {
            Microsoft.Feeds.Interop.FeedsManager manager = new FeedsManagerClass();

            List<Outline> rootFolders = new List<Outline>();

            rootFolders.Add(ParseFolder(manager.RootFolder as IFeedFolder));

            Head header = new Head();
            header.Title = "Feed Store OPML";
            header.OwnerName = Environment.UserName;
            header.DateCreated = DateTime.Now;

            OPML opml = new OPML();

            opml.Body.AddRange(rootFolders);
            opml.Head = header;
            return opml;
        }

        private static void ParseFeed(Outline parent, IFeed feed)
        {
            try
            {
                Outline subOutline = new Outline();
                subOutline.Title = feed.Title;
                subOutline.HtmlUrl = feed.Link;
                subOutline.XmlUrl = feed.Url;

                parent.AddSubItem(subOutline);
            }
            catch
            {
            }
        }

        private static Outline ParseFolder(IFeedFolder folder)
        {
            Outline outline = new Outline();
            outline.Text = folder.Name;

            foreach (IFeedFolder subFolder in folder.Subfolders as IFeedsEnum)
            {
                outline.AddSubItem(ParseFolder(subFolder));
            }
            foreach (IFeed feed in folder.Feeds as IFeedsEnum)
            {
                ParseFeed(outline, feed);
            }
            return outline;
        }
    }
}